package com.huang.core.widget.recyclerview.listener

import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.huang.core.widget.recyclerview.layoutmanager.MultiLinearLayoutManager

abstract class OnScrollBorderListener<T : RecyclerView.ViewHolder>(
        private val adapter: RecyclerView.Adapter<*>,
        private val topBorderCount: Int = -1,   //监听滚动到顶部的Item偏移量，<-1时关闭
        private val bottomBorderCount: Int = 1    //监听滚动到底部的Item偏移量
) : RecyclerView.OnScrollListener() {

    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
        super.onScrolled(recyclerView, dx, dy)
        onScrollListener(recyclerView, getScrollHeight(recyclerView))
    }

    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
        super.onScrollStateChanged(recyclerView, newState)
        val layoutManager = recyclerView.layoutManager as LinearLayoutManager

        if (newState == RecyclerView.SCROLL_STATE_IDLE)
            if (layoutManager.findFirstVisibleItemPosition() == topBorderCount) {
                onScrollTopListener(recyclerView)
            } else if (layoutManager.findFirstVisibleItemPosition() == adapter.itemCount - bottomBorderCount) {
                onScrollBottomListener(recyclerView)
            }
    }

    open fun onScrollListener(recyclerView: RecyclerView, height: Int) {

    }

    open fun onScrollTopListener(recyclerView: RecyclerView) {

    }

    open fun onScrollBottomListener(recyclerView: RecyclerView) {

    }

    /** 需要使用内容中的响应的LayoutManager才有获取滚动距离的效果  */
    private fun getScrollHeight(recyclerView: RecyclerView): Int {
        if (recyclerView.layoutManager is MultiLinearLayoutManager) {
            return (recyclerView.layoutManager as MultiLinearLayoutManager).computeVerticalHeight()
        } else return 0
    }

}